package com.studio.bill.swiperecyclerdemo;

import android.app.Activity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.studio.bill.swiperecyclerdemo.Constants.URLConstants;
import com.studio.bill.swiperecyclerdemo.adapter.RecyclerViewDemoAdapter;
import com.studio.bill.swiperecyclerdemo.bean.NonInsuranceBean;
import com.studio.bill.swiperecyclerdemo.util.DataRequestUtil;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{

    private int mPageNo = 0;
    private static final String TAG="swipe_demo";
    private RecyclerViewDemoAdapter mAdapter;
    private List<NonInsuranceBean> mList = new ArrayList<NonInsuranceBean>();
    private int lastVisibleItem;
    private SwipeRefreshLayout mSwipeRefreshLayout = null;
    private RecyclerView mRecyclerView = null;
    private DataRequestUtil mDataRequestUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDataRequestUtil = DataRequestUtil.getInstance();

        initView();

        initData();
    }

    private void initView(){
        mAdapter = new RecyclerViewDemoAdapter(this,mList);
        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.srl_main);
        mRecyclerView = (RecyclerView)findViewById(R.id.ryv_main);

        //设置OnRefresh的监听器，也就是实现OnRefresh的类
        mSwipeRefreshLayout.setOnRefreshListener(this);

        //设置固定大小
        mRecyclerView.setHasFixedSize(true);

        //创造线性布局，线性布局用来管理item的排列方式
        //也可以用GridLayoutManger等其他布局管理器
        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置Item的布局方向为垂直方向
        mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        //设置默认动画效果
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置数据Adapter
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener(){
            /*当滚动状态发生迁移的时候，会调用该方法，比如说，从 SCROLL_STATE_SETTING 迁移到 SCROLL_STATE_IDLE*/
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                Log.d("swipe_demo","new state " + getScrollState(newState));

                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mAdapter.getItemCount()) {

                    //设置刷新状态为true
                    mSwipeRefreshLayout.setRefreshing(true);

                    //实际项目中这里一般是用网络请求获取数据
                    mPageNo = mPageNo + 1;
                    loadNonInsuranceData(mPageNo);
                }
            }

            /*
            *   以下两种情况会调用该方法
            *   (1)显示的item的index范围发生变化时。
            *       如果是纵向滚动，dx为0，dy > 0时表示向下滚动时刷出的item数量，dy < 0表示向上的。
            *       如果是横向滚动，dx > 0表示向右滚动的item的数量,dx < 0表示向左的，dy为0
            *
            *   (2)当显示的item超出当前的layoutmannager计算范围时，则 dx,dy均为0
            * */
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d(TAG,"onScrolled  dx : " + dx + " dy: " + dy);
                //判断是当前layoutManager是否为LinearLayoutManager
                //只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (mLayoutManager instanceof LinearLayoutManager) {
                    //获取最后一个可见view的位置
                    lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
                }
            }
        });

    }

    private void loadNonInsuranceData(int pageIndex){
        JSONObject params = new JSONObject();
        try{
            params.put("pageSize",5);
            params.put("pageIndex",pageIndex);
            params.put("city","深圳");
        }catch (Exception e){
            e.printStackTrace();
        }

        mDataRequestUtil.requestPost(URLConstants.URL_GET_NON_AUTO_INSURANCE, params.toString(), new DataRequestUtil.Callback() {
            @Override
            public void onSucceeded(String json) {
                mSwipeRefreshLayout.setRefreshing(false);

                Log.i(TAG,"获取非车险推荐列表成功 " + json);
                //在Adapter里面添加数据
                List<NonInsuranceBean> nonInsuranceBeanList = NonInsuranceBean.getNonInsuranceData(json);
                if(nonInsuranceBeanList == null || nonInsuranceBeanList.size() == 0){
                    mPageNo = mPageNo > 0 ? mPageNo - 1 : 0;
                    return;
                }
                mList.addAll(nonInsuranceBeanList);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, int resultCode) {
                mSwipeRefreshLayout.setRefreshing(false);
                Log.i(TAG, "获取非车险推荐列表失败：" + msg);
                mPageNo = mPageNo > 0 ? mPageNo - 1 : 0;
            }
        });
    }


    @Override
    public void onRefresh() {
        Log.d("swip_demo","swipe onRefresh ....");
        //实际项目中这里一般是用网络请求获取数据
        mAdapter.notifyDataSetChanged();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    private String getScrollState(int newState){
        switch(newState){
            //外力拖动的时候触发dragging状态
            case RecyclerView.SCROLL_STATE_DRAGGING:
                return "SCROLL_STATE_DRAGGING";
            //外力停止后，停止滑动前的状态就是 setting状态
            case RecyclerView.SCROLL_STATE_SETTLING:
                return "SCROLL_STATE_SETTLING";
            //停止滑动的状态idle
            case RecyclerView.SCROLL_STATE_IDLE:
                return "SCROLL_STATE_IDLE";
        }

        return Integer.toString(newState);
    }

    private void initData(){
        mPageNo = 0;
        loadNonInsuranceData(0);
    }
}
